#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "wifi_connect.h"
#include "mqtt_client.h"
#include "camera.h"
#include "temperature_sensor.h"

static const char *TAG = "MAIN";

void app_main(void)
{
    ESP_LOGI(TAG, "Initializing ESP32-CAM MQTT application");
    
    // Initialize NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    
    // Initialize WiFi
    wifi_init_sta();
    
    // Initialize Camera
    camera_init();
    
    // Initialize Temperature Sensor
    temperature_sensor_init();
    
    // Initialize MQTT Client
    mqtt_app_start();
    
    // Main loop
    while (1) {
        // Take photo and send via MQTT every 30 seconds
        capture_and_send_photo();
        
        // Read and send temperature every 10 seconds
        float temp = read_temperature();
        mqtt_send_temperature(temp);
        
        vTaskDelay(10000 / portTICK_PERIOD_MS);
    }
}